package com.cloudkinto.controller.user;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cloudkinto.base.BaseController;
import com.cloudkinto.common.common.MD5Util;
import com.cloudkinto.common.constant.SysConstant;
import com.cloudkinto.common.exception.BizException;
import com.cloudkinto.common.exception.BizExceptionI18;
import com.cloudkinto.common.web.SingleResult;
import com.cloudkinto.dao.UserDao;
import com.cloudkinto.entity.UserDo;
import com.cloudkinto.entity.WxUserDo;
import com.cloudkinto.service.user.WxUserService;
import com.cloudkinto.service.user.wxvo.WxTokenByCodeEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zhangyy
 * @since 2020-10-10
 */
@RestController
@Api(tags = "微信公众号模块")
@RequestMapping("/api/weChat")
public class WxUserController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(WxUserController.class);

    @Autowired
    private WxUserService service;
    @Autowired
    private UserDao userDao;

    @GetMapping("/getAccessTokenByCode")
    @ApiOperation(value = "根据code获取token在获取user信息", notes = "根据code获取token在获取user信息")
    public SingleResult getTokenByCode(@RequestParam String code, @RequestParam String userAccount, @RequestParam String password) {
        MD5Util md5 = new MD5Util(SysConstant.SALT_STRING, "MD5");
        LambdaQueryWrapper<UserDo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserDo::getUserAccount, userAccount)
                .eq(UserDo::getUserPassword, md5.encode(password));

        UserDo userDo = userDao.selectOne(wrapper);
        if (userDo == null) {
            throw new BizExceptionI18(SysConstant.Login_Error_AccountPassword);
        }
        //1.根据code获取token以及openid
        WxTokenByCodeEntity wxTokenByCodeEntity = service.getAccessTokenByCode(code);
        //获取微信用户信息并保存
        WxUserDo userInfoByToken = service.getUserInfoCommonByToken(wxTokenByCodeEntity.getOpenid());

        return SingleResult.success(userInfoByToken);
    }


    @GetMapping("/getJSDKSign")
    @ApiOperation(value = "根据url获取sign", notes = "根据url获取sign")
    public SingleResult getJSDKSign(@RequestParam String url) {
        return SingleResult.success(service.getJSDKSign(url));
    }


}

